package day6.volatile_demo;

import java.util.concurrent.TimeUnit;
/**
 * volatile保证内存可见性的例子
 */
public class Demo {
    // 保证内存可见性
    public static volatile boolean flag = true;

    static class Thread1 extends Thread {
        @Override
        public void run() {
            while (flag) {
                // 一直循环，等待flag被改变
            }
            System.out.println("线程1发现flag被改变了。。。");
        }
    }
    static class Thread2 extends Thread {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = false;
            System.out.println("线程2修改了flag的值。。。");
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread1 t1 = new Thread1();
        Thread2 t2 = new Thread2();
        t2.start();
        t1.start();
    }
}
